package leetcode_core.leetcode_2;

import org.junit.Test;

import java.util.*;

public class TopKFrequent {
    public int[] topKFrequent(int[] nums, int k) {
        if(nums.length == 1){
            return new int[]{nums[0]};
        }
        Arrays.sort(nums);
        //System.out.println(Arrays.toString(nums));
        Map<Integer,Integer> map = new HashMap<>();
        PriorityQueue<Integer> set = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return map.get(o2)-map.get(o1);
            }
        });
        int slow = 0 ,fast = 1;
        while (slow < nums.length){
            if(fast == nums.length){
                map.put(nums[slow],map.getOrDefault(nums[slow],0)+1);
                set.remove(nums[slow]);
                set.add(nums[slow]);
                slow++;
            }else{
                if(nums[slow] == nums[fast]){
                    fast++;
                }else{
                    int count = fast - slow;
                    map.put(nums[slow],count);
                    set.remove(nums[slow]);
                    set.add(nums[slow]);
                    slow = fast;
                    fast++;
                }
            }
        }
        int[] arr = new int[k];int i=0;
        System.out.println(Arrays.toString(set.toArray()));
        for (Integer integer : set) {
            arr[i++] = integer;
            if(i== k){
                break;
            }
        }
        return arr;
    }

    @Test
    public void test(){
        //System.out.println(Arrays.toString(topKFrequent(new int[]{1,2,2,3,3,3,3,4,4},3)));
        //System.out.println(Arrays.toString(topKFrequent(new int[]{1,1,1,1,2,2},1)));
        //System.out.println(Arrays.toString(topKFrequent(new int[]{1,2},2)));
        System.out.println(Arrays.toString(topKFrequent(new int[]{4,1,-1,2,-1,2,3},2)));
        /**
         *
         */
    }

}
